// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use log::{error, info, warn};
use std::process;

mod database;
mod domain;
mod repository;
mod service;
mod common;

/// 运行 Tauri 应用的主要逻辑
///
/// # 参数列表
/// * None
///
/// # 返回结果
/// * Result<(), Box<dyn std::error::Error>>
fn run_tauri_app() -> Result<(), Box<dyn std::error::Error>> {
    tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
        service::add_app,
        service::get_apps,
        service::get_app,
        service::edit_app,
        service::delete_app,
        service::get_charts,
        service::download_file,
        service::helm::get_helm_version,
        service::kubectl::get_kubectl_version,
        service::env_path::get_login_shell_path
    ])
        .setup(|_app| {
            info!("Tauri 应用设置完成");
            Ok(())
        })
        .run(tauri::generate_context!())
        .map_err(|e| e.into())
}

fn main() {
    let config = common::logger::AppConfig {
        log_level: "info".to_string(),
        app_name: "ChartsManager".to_string(),
    };

    // 1. 初始化日志系统
    if let Err(e) = common::logger::setup_logging(&config) {
        eprintln!("日志系统初始化失败: {}", e);
        process::exit(1);
    }

    // 2. 设置优雅关闭
    setup_shutdown_hooks();

    // 3. 初始化数据库
    if let Err(e) = database::setup_database() {
        error!("应用启动失败: {}", e);
        process::exit(1);
    }

    // 4. 启动 Tauri 应用
    info!("正在启动 Tauri 应用...");

    if let Err(e) = run_tauri_app() {
        error!("Tauri 应用运行失败: {}", e);
        process::exit(1);
    }

    info!("应用已正常退出");
}

/// 优雅关闭处理
fn setup_shutdown_hooks() {
    ctrlc::set_handler(move || {
        info!("接收到关闭信号，正在优雅退出...");
        process::exit(0);
    }).unwrap_or_else(|e| {
        warn!("无法设置Ctrl-C处理器: {}", e);
    });
}